package com.dhl.fin.api.controller;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author CuiJianbo
 * @since 2025/4/1
 */
@Slf4j
@RestController
@RequestMapping("resoures")
public class ResourceController {

    @Value("${custom.resources}")
    private String resourcePath;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @GetMapping("/**")
    public void getConsultChatData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filename = request.getRequestURI().replaceAll(contextPath + "/resoures/remind", "");
        String filePath = resourcePath + File.separator + filename;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            log.error("file not exist:{}", filePath);
            return;
        }

        response.setContentType(determineContentType(filename));
        StreamUtils.copy(fileInputStream, response.getOutputStream());

    }

    private String determineContentType(String filename) {
        if (filename.endsWith(".css")) {
            return "text/css";
        } else if (filename.endsWith(".js")) {
            return "application/javascript";
        } else if (filename.endsWith(".png")) {
            return "image/png";
        } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (filename.endsWith(".gif")) {
            return "image/gif";
        } else if (filename.endsWith(".svg")) {
            return "image/svg+xml";
        } else if (filename.endsWith(".html")) {
            return "text/html";
        } else if (filename.endsWith(".json")) {
            return "application/json";
        } else {
            return "application/octet-stream";
        }
    }

}
